/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Control;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Duc Quyen
 */
public class SendMailToEmployer extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, MessagingException {
        
        MultipartRequest mt = null;
        String encType = "utf-8";
        String folder = getServletContext().getRealPath("\\upload");
        int maxSize = 5 * 1024 * 1024;
        mt = new MultipartRequest(request, folder, maxSize, encType, new DefaultFileRenamePolicy());

        String jobSeekerName = mt.getParameter("jsname");
        String mailEmployer = mt.getParameter("mailemp");
        String mailJobseeker = mt.getParameter("mailjs");
        String subject = mt.getParameter("titleapply");
        String letter = mt.getParameter("letter");
        String file = getServletContext().getRealPath("\\upload") + "\\" + mt.getParameter("dispName");
        int jobID = Integer.parseInt(mt.getParameter("jobID"));
        String body = "Họ và tên người ứng tuyển: " + jobSeekerName + ".\n" + "Email: " + mailJobseeker + ".\n";
        body += "Thư giới thiệu: " + "\n" + letter;
        System.out.println("ten file la " +mt.getParameter("dispName"));
        boolean result = !mt.getParameter("dispName").equals("")?send("localhost", "admin@myhost.com", mailEmployer, null, subject, body, file):
            send("localhost", "admin@myhost.com", mailEmployer, null, subject, body, null);
        if(mt.getParameter("dispName")!=null){
        File f = new File(file);
        f.delete();
        }
        if (result) {
            request.setAttribute("result", "<span style='color:red'>Bạn đã nộp đơn ứng tuyển thành công</span>");
        } else {
            request.setAttribute("result", "<span style='color:red'>Rất tiếc đơn ứng tuyển của bạn đã gửi không thành công</span>");
        }
        String url = "/applyonline.jsp?jobID=" + jobID;
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }

    public static boolean send(String smtpServer, String from, String to, String password, String subject, String body, String fileName) throws MessagingException {
        boolean result = true;
        Properties pro = System.getProperties();
        pro.put("mail.smtp.host", smtpServer);
        pro.put("mail.smtp.port", 25);
        Session session = Session.getInstance(pro, null);
        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject, "UTF-8");
//        message.setText(body,"UTF-8");
        MimeBodyPart mbp1 = new MimeBodyPart();
        Multipart mp = new MimeMultipart();
        mbp1.setText(body,"UTF-8");
        mp.addBodyPart(mbp1);
        if(fileName!=null){
        MimeBodyPart mbp2 = new MimeBodyPart();
        FileDataSource fds = new FileDataSource(fileName);
        mbp2.setDataHandler(new DataHandler(fds));
        mbp2.setFileName(fds.getName());
         mp.addBodyPart(mbp2);
        }
       
        message.setContent(mp);
        message.setSentDate(new Date());
//        Transport.send(message);

        Transport tran = session.getTransport("smtp");
        try {
            tran.connect(smtpServer, from, password);
            tran.sendMessage(message, message.getAllRecipients());
            tran.close();
        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        }
        return result;

    }
    public static void main(String[] args) throws MessagingException {
         send("localhost", "admin@myhost.com", "quyen@myhost.com", null, "I love you", "Don xin viec", "E:\\calendar.png");

    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request public static void main(String[] args) throws MessagingException {
    send("localhost", "admin@myhost.com", "quyen@myhost.com", null, "I love you", "Don xin viec", "E:\calendar.png");
    }
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (MessagingException ex) {
            Logger.getLogger(SendMailToEmployer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (MessagingException ex) {
            Logger.getLogger(SendMailToEmployer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
